#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/types.h>

#define LINE_SIZE 1024
#define LEFT "["
#define RIGHT "]"
#define LABLE "$"
#define DELIM " \t"
#define ARGC_SIZE 32

char* argv[ARGC_SIZE];
char commandline[LINE_SIZE];
char pwd[LINE_SIZE];
char myenv[LINE_SIZE];
int lastcode;

void GetPwd(){
  getcwd(pwd,sizeof(pwd)); 
}

char* GetHostName(){
  return getenv("HOSTNAME");
}

char* GetUser(){
  return getenv("USER");
}

void Interact(char* cline,int size){
  GetPwd();
  printf(LEFT"%s@%s %s" RIGHT LABLE" ",GetUser(),GetHostName(),pwd);
  char* s=fgets(cline,size,stdin); 
  assert(s);
  (void)s;
  cline[strlen(cline)-1]='\0';
}

int SplitString(char* cline,char* _argv[]){
  int i=0;
  _argv[i++]=strtok(cline,DELIM);
  while(_argv[i++]=strtok(NULL,DELIM));
  return i-1;
}

int BuildCommand(int _argc,char* _argv[]){
  if(_argc==2&&strcmp(_argv[0],"cd")==0){
    chdir(_argv[1]);
    GetPwd();
    sprintf(getenv("PWD"),"%s",pwd);
    return 1;
  }
  else if(_argc==2&&strcmp(_argv[0],"export")==0){
    strcpy(myenv,_argv[1]);
    putenv(myenv);
    return 1;
  }
  else if(_argc==2&&strcmp(_argv[0],"echo")==0){
    if(strcmp(_argv[1],"$?")==0){
      printf("%d\n",lastcode);
      lastcode=0;
    }
    else if(*_argv[1]=='$'){
      char* val=getenv(_argv[1]+1);
      if(val) printf("%s\n",val);
    }
    else{
      printf("%s\n",_argv[1]);
    }
    return 1;
  }
  //特殊处理一下"ls"
  if(strcmp(_argv[0],"ls")==0){
    _argv[_argc++]="--color";
    _argv[_argc]=NULL;
  }
  return 0;
}

void NomalExcute(char* _argv[]){
  pid_t id=fork();
  if(id<0){
    perror("fork error");
    return;
  }
  else if(id==0){
    execvp(_argv[0],_argv);
    exit(0);
  }
  else{
    int status;
    pid_t ret=waitpid(-1,&status,0);
    if(ret==id){
      lastcode=WEXITSTATUS(status);
    }
  }
}

int main(){
  while(1){
    //交互命令，获取命令行
    Interact(commandline,sizeof(commandline));
    //子串分割，解析命令行
   int argc=SplitString(commandline,argv);
   if(argc==0) continue;
   //指令的判断,本质上就是一个shell内部的函数
   int n=BuildCommand(argc,argv);
   // 普通命令的执行
   if(!n) NomalExcute(argv);
  }

  return 0;
}
